# -*- coding: utf-8 -*-
import numpy as np
import cv2
def cv_show(img,name,writename):#
    cv2.imshow(name,img)
    cv2.imwrite(writename,img)
    cv2.waitKey()
    cv2.destroyAllWindows()

img = cv2.imread('contours2.png')#读取图片
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#灰度图
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)#对灰度图二值化
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)#绘制图像轮廓
cnt = contours[0]#取第一个轮廓结果
#1.绘制轮廓
#传入绘制图像，轮廓，轮廓索引，颜色模式，线条厚度
#注意需要copy原图，因为处理的时候会修改原图
# draw_img = img.copy()
# res = cv2.drawContours(draw_img,[cnt],-1,(0,0,255),2)##0：外轮廓，-1指全部轮廓，1指内轮廓(0,0,255)为BGR颜色，2为线条宽度
# cv_show(res,'res','contours.png')

# 2.近似轮廓
esiplon1 = 0.1*cv2.arcLength(cnt,True)#参数越小近似轮廓越接近
approx1 = cv2.approxPolyDP(cnt,esiplon1,True)
draw_img1 = img.copy()
res1 = cv2.drawContours(draw_img1,[approx1],-1,(0,0,255),2)##0：外轮廓，-1指全部轮廓，1指内轮廓(0,0,255)为BGR颜色，2为线条宽度

esiplon2 = 0.01*cv2.arcLength(cnt,True)#参数越小近似轮廓越接近
approx2= cv2.approxPolyDP(cnt,esiplon2,True)
draw_img2= img.copy()
res2 = cv2.drawContours(draw_img2,[approx2],-1,(0,0,255),2)##0：外轮廓，-1指全部轮廓，1指内轮廓(0,0,255)为BGR颜色，2为线条宽度


res = np.hstack((img,res1,res2))
cv_show(res,'res','contours2233.png')
